package com.hyjy.music.fragment

import com.hyjy.music.base.BaseFragment
import android.animation.ObjectAnimator
import com.hyjy.music.receiver.MediaVolumeReceiver
import android.view.LayoutInflater
import android.media.AudioManager
import android.widget.SeekBar.OnSeekBarChangeListener
import android.widget.SeekBar
import android.content.IntentFilter
import android.view.animation.LinearInterpolator
import android.animation.ValueAnimator
import android.content.Context
import com.hyjy.music.R
import android.graphics.BitmapFactory
import android.os.Bundle
import android.view.animation.Animation
import android.view.animation.AnimationUtils
import com.hyjy.music.bean.MusicBean
import com.hyjy.music.databinding.FragmentPhotoBinding

/**
 * 封面专辑Fragment
 */
class PhotoFragment : BaseFragment<FragmentPhotoBinding>() {
    companion object {
        fun newInstance(): PhotoFragment {
            val fragment = PhotoFragment()
            val args = Bundle()
            fragment.arguments = args
            return fragment
        }
    }

    private val animationExit: Animation by lazy {
        AnimationUtils.loadAnimation(context, R.anim.photo_exit)
    }

    private val animationEnter: Animation by lazy {
        AnimationUtils.loadAnimation(context, R.anim.photo_enter)
    }

    private lateinit var mainFragment: MainFragment
    private var objectAnimator: ObjectAnimator? = null
    private var receiver: MediaVolumeReceiver? = null

    private var url = ""

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        mainFragment = requireParentFragment() as MainFragment
    }

    override fun initViewBinding(inflater: LayoutInflater): FragmentPhotoBinding {
        return FragmentPhotoBinding.inflate(inflater)
    }

    override fun initData() {
        val audioManager = context?.getSystemService(Context.AUDIO_SERVICE) as AudioManager
        val maxVoice = audioManager.getStreamMaxVolume(AudioManager.STREAM_MUSIC)
        val currentVoice = audioManager.getStreamVolume(AudioManager.STREAM_MUSIC)
        binding?.voiceSeekBar?.max = maxVoice
        binding?.voiceSeekBar?.progress = currentVoice
        binding?.voiceSeekBar?.setOnSeekBarChangeListener(object : OnSeekBarChangeListener {
            override fun onProgressChanged(seekBar: SeekBar, progress: Int, fromUser: Boolean) {
                if (fromUser) {
                    // 第三个参数如果传1,则滑动SeekBar时,系统的音量调节界面也会显示出来
                    audioManager.setStreamVolume(AudioManager.STREAM_MUSIC, progress, 1)
                }
            }

            override fun onStartTrackingTouch(seekBar: SeekBar) {}
            override fun onStopTrackingTouch(seekBar: SeekBar) {}
        })

        // 注册广播接收者
        receiver = MediaVolumeReceiver {
            binding?.voiceSeekBar?.progress = this
        }
        val filter = IntentFilter()
        filter.addAction("android.media.VOLUME_CHANGED_ACTION")
        context?.registerReceiver(receiver, filter)

        // 初始化动画
        objectAnimator = ObjectAnimator.ofFloat(
            binding?.circleImageView, "rotation", 0f, 360f
        ).apply {
            duration = 24000L // 旋转一圈时间
            interpolator = LinearInterpolator()
            repeatCount = -1 // 转动圈数
            repeatMode = ValueAnimator.RESTART // 旋转模式
        }
        objectAnimator?.start() // 开始动画
    }

    override fun onDestroy() {
        super.onDestroy()
        context?.unregisterReceiver(receiver)
        objectAnimator?.cancel()
        objectAnimator = null
    }

    fun updateUI(musicBean: MusicBean?) {
        if (url != musicBean?.url) {
            url = musicBean?.url ?: ""
            // 音乐切换动画
            binding?.circleImageView?.startAnimation(animationExit)
            animationExit.setAnimationListener(object : Animation.AnimationListener {
                override fun onAnimationStart(animation: Animation?) {}
                override fun onAnimationRepeat(animation: Animation?) {}
                override fun onAnimationEnd(animation: Animation?) {
                    setPhotoBackground(musicBean)
                    binding?.circleImageView?.startAnimation(animationEnter)
                }
            })
        }
        // 根据播放状态，开启或者暂停动画
        if (mainFragment.myBinder?.isMusicPlaying() == true) {
            objectAnimator?.resume()
        } else {
            objectAnimator?.pause()
        }
    }

    private fun setPhotoBackground(musicBean: MusicBean?) {
        musicBean?.embedPic?.let {
            val bitmap = BitmapFactory.decodeByteArray(it, 0, it.size)
            binding?.circleImageView?.setImageBitmap(bitmap)
        } ?: kotlin.run {
            binding?.circleImageView?.setImageResource(R.drawable.ic_baseline_music_background_white)
        }
    }
}